package org.kotboot.service;

import org.kotboot.cons.ConsJwt;
import org.kotboot.dao.UserDao;
import org.kotboot.domain.User;
import org.kotboot.enums.BoolState;
import org.kotboot.enums.ESignTypeBak;
import org.kotboot.kit.*;
import org.kotboot.module.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * jisong.sun 2017/9/14 16:10
 */

@Service
public class SignServBak {

    private static Logger log = LoggerFactory.getLogger(SignServBak.class);

    @Resource
    SecretServ secretServ;
    @Resource
    UserServ userServ;
    @Resource
    UserDao userDao;
    @Autowired
    ConsJwt consJwt;

    /**
     * 登录操作
     * @param params
     * @return
     */
    public R signin(KMap params) {
        log.info("登录请求，参数：{}",params);
        R<User> validRes = validParams(params);
        if(validRes.isErr()) return validRes;
        User user = validRes.getObj();
        return _signIn(user);
    }

    /**
     * 登录，返回stoken
     * @param user
     * @return
     */
    private R _signIn(User user) {
        KMap map = new KMap();
        map.put("userid",user.getId());
        map.put("avator",user.getAvator());
        map.put("nickname",user.getNickname());
        String stoken = consJwt.create(map.toString());
        KMap res = new KMap();
        res.put("stoken",stoken);
        return R.OK(res);
    }

    /**
     * 登录参数验证
     * @param params
     * @return
     */
    private R validParams(KMap params) {
        String name = params.getString("name");
        //密码加密key的版本号
        String ver = params.getString("ver");
        String type = params.getString("type");
        log.info("登录，session key 的版本号：{},登录类型：{}",ver,type);
        ESignTypeBak etype = ESignTypeBak.of(type);
        if(K.isEmpty(etype)){
            return R.ER("不支持的操作类型！");
        }
        User user = null;
        //登录类型，手动号加短信码，手机号加密码，邮件加验证码，邮件加密码
        if(ESignTypeBak.mobile(etype)){
            if(!RegKit.isMoble(name)){
                return R.ER("手动号码格式错误");
            }
            user = userServ.findByMob(name);
        }
        if(ESignTypeBak.mail(etype)){
            if(!RegKit.isMail(name)){
                return R.ER("邮箱格式错误！");
            }
            user = userServ.findByMail(name);
        }
        log.info("登录,查询会员 : 结果: {}",user);
        if(null == user){
            return R.ER("会员不存在");
        }
        switch (etype){
            case MOB_SMS:
                String smscode = params.getString("smscode");
                R r = validCode(name, smscode);
                if(r.isErr()) return r;
                break;
            case MOB_PWD:
                String sessionKey = secretServ.sessionKey(ver);
                String session = params.getString("_session");
                if(K.Str.isEmpty(session)){
                    return R.ER("登录异常，联系客服。");
                }
                String decrypt = AES.decrypt(session, sessionKey);
                log.info("登录解密后的数据：{}",decrypt);

                KMap map = K.toMap(decrypt);
                String password = map.getString("password");
                if(K.isEmpty(password)){
                    return R.ER("密码不能为空");
                }
                String pwd = user.getPassword();
                String salt = user.getSalt();
                boolean equals = PwdKit.equals(password, pwd, salt);
                if(!equals){
                    return R.ER("密码错误!");
                }
                break;
            case MAIL_PWD:
                return R.ER("未支持的操作");
            case MAIL_CODE:
                return R.ER("未支持的操作");
        }
        return R.OK("验证成功",user);
    }

    /**
     * 注册操作
     * @param params
     * @return
     */
    public R signup(KMap params) {
        log.info("注册请求，参数：{}",params);
        R validRes = singupValid(params);
        if(validRes.isErr()){
            return validRes;
        }
        String name = params.getString("name");
        return _signUp(name);
    }

    private R singupValid(KMap params) {
        String name = params.getString("name");
        String type = params.getString("type");
        log.info("注册,注册类型：{}",type);
        ESignTypeBak etype = ESignTypeBak.of(type);
        if(K.isEmpty(etype)){
            return R.ER("不支持的操作类型！");
        }
        if(ESignTypeBak.mobile(etype) && !RegKit.isMoble(name)){
            return R.ER("手动号码格式错误");
        }
        if(ESignTypeBak.mail(etype) && !RegKit.isMail(name)){
            return R.ER("邮箱格式错误！");
        }
        switch (etype){
            case MOB_SMS:
                String smscode = params.getString("smscode");
                R codeRes = validCode(name,smscode);
                if(codeRes.isErr()){
                    return codeRes;
                }
                break;
            case MOB_PWD:

                return R.ER("未支持的操作");
            case MAIL_PWD:
                return R.ER("未支持的操作");
            case MAIL_CODE:
                return R.ER("未支持的操作");
        }
        return R.OK("验证成功");
    }

    /**
     * 注册成功，生成新用户，并且返回新的stoken
     * @param name
     * @return
     */
    private R _signUp(String name) {
        User in_user = new User();
        in_user.setMobile(name);
        in_user.setDel(BoolState.NO);
        in_user.setAvator(AvatorKit.random());
        in_user.setNickname(K.Str.encryptMobile(name));
        in_user.setCtime(new Date());
        in_user.setUtime(new Date());
        int line = userDao.insertSelective(in_user);
        return _signIn(in_user);
    }

    private R validCode(String name, String smscode) {
        if("465531".equals(smscode)){
            return R.OK();
        }
        return R.ER("验证码错误");
    }

    /**
     * 获取短信 验证码
     * @param params
     * @return
     */
    public R smsCode(KMap params) {
        return R.OK();
    }
}
